package com.kaishengit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kaishengit.entity.User;
import com.kaishengit.util.DBHelp;
import com.kaishengit.util.RowMapper;

public class UserDao {
	DBHelp<User> db = new DBHelp<User>();
	public User getname(String id){
		String sql="select id,username,`password`,email,pic from t_user where id=?";
		return db.executeQueryForObject(sql, new UserRowMapper(), id);
	}
	public User findUserByEmailAndPassword(String email,String password) {
		String sql = "SELECT id,username,`password`,email,pic FROM t_user WHERE email=? AND `password`=?";
		return db.executeQueryForObject(sql, new UserRowMapper(),email,password);
	}
	
	public boolean save(User user) {
		String sql = "INSERT INTO t_user (id,username,`password`,email,pic) VALUES (?,?,?,?,?)";
		return db.executeSQL(sql, user.getId(),user.getUsername(),user.getPassword(),user.getEmail(),user.getPic());
	}
	
	public boolean update(User user) {
		String sql = "UPDATE t_user SET username=?,`password`=?,email=?,pic=? WHERE id=?";
		return db.executeSQL(sql, user.getUsername(),user.getPassword(),user.getEmail(),user.getPic(),user.getId());
	}
	
	public List<User> findAll() {
		String sql = "SELECT id,username,`password`,email,pic FROM t_user";
		return db.executeQueryForList(sql, new UserRowMapper());
	}
	
	public List<User> findByProId(String proId) {
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT tu.id,tu.username,tu.password,tu.email,tu.pic FROM t_user_project AS tup ");
		sql.append("LEFT JOIN t_user AS tu ON tu.id=tup.t_user_id ");
		sql.append("WHERE tup.t_project_proId=?");
		return db.executeQueryForList(sql.toString(), new UserRowMapper(), proId);
	}

	
	private class UserRowMapper implements RowMapper<User> {

		public User mapRow(ResultSet rs) throws SQLException {
			User user = new User();
			user.setId(rs.getString("id"));
			user.setUsername(rs.getString("username"));
			user.setPassword(rs.getString("password"));
			user.setEmail(rs.getString("email"));
			user.setPic(rs.getString("pic"));
			return user;
		
		}
		
	}

	
}